package com.zuiacsn.forum.controller;

import com.zuiacsn.forum.common.AppResult;
import com.zuiacsn.forum.common.ResultCode;
import com.zuiacsn.forum.config.AppConfig;
import com.zuiacsn.forum.model.Article;
import com.zuiacsn.forum.model.ArticleReply;
import com.zuiacsn.forum.model.User;
import com.zuiacsn.forum.service.IArticleReplayService;
import com.zuiacsn.forum.service.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags = "回复接口")
@RestController
@RequestMapping("/reply")
@Slf4j
public class ArticleReplyController {

    @Autowired
    IArticleService articleService;
    @Autowired
    IArticleReplayService articleReplayService;

    @ApiOperation("回复帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam(value = "articleId") @NonNull Long articleId,
                            @ApiParam("帖子内容") @RequestParam(value = "content") @NonNull String content){
        // 获取用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断用户是否已经被禁言
        if(user.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 获取帖子信息
        Article article = articleService.selectById(articleId);
        if(article == null || article.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        // 是否封贴
        if(article.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        // 写入回复信息
        ArticleReply articleReply = new ArticleReply();
        articleReply.setArticleId(articleId);
        articleReply.setContent(content);
        articleReply.setPostUserId(user.getId());
        articleReplayService.create(articleReply);
        return AppResult.success();
    }


    @ApiOperation("查询帖子列表")
    @GetMapping("/getReplies")
    public AppResult getRepliesByArticleId(@ApiParam("帖子id") @RequestParam(value = "articleId") @NonNull Long articleId){

        // 获取帖子信息
        Article article = articleService.selectById(articleId);
        if(article == null || article.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        List<ArticleReply> articleReplies = articleReplayService.selectByArticleId(articleId);
        return AppResult.success(articleReplies);
    }
}
